<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/3
 * Time: 11:04
 */
namespace app\index\controller;

use think\Request;
use think\Db;
use think\View;
use think\Loader;
use think\Session;
use think\Controller;

class Login extends Controller
{
    //用户登录
    public function login()
    {
        if (Session('Login_userId') != null) {
            $res['code'] = 'ok';
            $res['msg'] = '登陆成功';
            return  $res;
        }
        $providerId =  getProviderId();
        if(Request::instance()->method() == 'POST') {
            $data = $this->request->post();
            $where =  array(
                'memberName'=>$data['username'],
                'providerId'=>$providerId,
                'memberType'=>'0',
            );
            $user_info = Db::name("member")->where($where)->find();
            // 使用用户名、密码和状态的方式进行认证
            if(null === $user_info){
                $where =  array(
                    'mobile'=>$data['username'],
                    'providerId'=>$providerId,
                    'memberType'=>'0',
                );
                $user_info = Db::name("member")->where($where)->find();
                if (null === $user_info) {
                    $res['type'] = 'mobile';
                    $res['code'] = 'fail';
                    $res['msg'] = '帐号不存在或已禁用';
                    return $res;
                } else {
                    if ($user_info['loginPwd'] === pwd_hash($data['loginPwd'])) {
                        Session('Login_userId', $user_info['memberId']);
                        Session('Login_userName', $user_info['memberName']);
                        // 记录登录日志
                        $res['code'] = 'ok';
                        $res['msg'] = '登陆成功';
                        return  $res;
                    }else{
                        $res['type'] = 'password';
                        $res['code'] = 'fail';
                        $res['msg'] = '密码错误';
                        return $res;
                    }
                }
            }else{
                if ($user_info['loginPwd'] === pwd_hash($data['loginPwd'])) {
                    // 生成session信息
                    Session('Login_userId', $user_info['memberId']);
                    Session('Login_userName', $user_info['memberName']);
                    Session('Login_font', mobile()['phonefont']);
                    Session('Login_back', mobile()['phoneback']);
                    // 记录登录日志
                    $res['code'] = 'ok';
                    $res['msg'] = '登陆成功';
                    return  $res;
                }else{
                    $res['type'] = 'password';
                    $res['code'] = 'fail';
                    $res['msg'] = '密码错误';
                    return $res;
                }
            }

        } else {
            $code=getFooter();
            $this->view->assign('code',$code);
            return view('login');
        }
    }
    //会员是否注册+发送验证码
    public function checkMobile(){
        //获取平台服务商
        $sms_code = input('sms_code');
        $providerId =  getProviderId();
        $phone = input('phone');
            //是否注册为会员
            $where2 = array(
                'mobile' => $phone,
                'providerId' => $providerId,
            );
            $user2 = Db::name('member')->where($where2)->find();
            if($user2 ==''){
                //发送验证码
                $SmsSend = new \app\index\controller\SmsSend();
                $res =  $SmsSend -> index($sms_code,$phone);
            }else{
                $res['code'] = 'fail';
                $res['msg'] = '该手机号已经被注册';
            }

        return $res   ;
    }
    //用户注册
    public function register()
    {

        if(Request::instance()->method() == 'POST') {
            //检查短信验证码
            $providerId =  getProviderId();
            $sms_code = input('smsCode');
            $phone = input('mobile');
            if($sms_code == Session($phone.'_smsCode')){
                //查询该手机号验证码是否过期
                $sendTime =  Session($phone.'_sendTime') ;
                $nowTime =  time();
                $sms_code_expire  =   Db::name('param')->where(array('paramCode' => 'VERIFY_CODE_INPUT_LIMIT','isEnable' => '1'))->value('paramValue');
                if($nowTime - $sendTime < ($sms_code_expire * 60)){
                    //生成个人邀请码，测试数据,$providerId 服务商Id
                    $invitationCode =  getInvitationCode();
                    // $invitationCode =   create_code($providerId.$phone);
                    //区域,服务商区域为会员区域
                    $areaId =  getProviderAreaId();
                    //根据推荐码查找推荐人信息
                    $postInvitationCode = input('invitationCode');
                    //不填写推荐码，默认推荐人服务商，填写了，查找推荐人
                    if($postInvitationCode ==""){
                           $inviterId  = "";
                    }else{
                            $where2 = array(
                                'invitationCode' => $postInvitationCode,
                            );
                            $inviter =  Db::name('member')->where($where2)->cache(false)->value('memberId');
                            //查找推荐人为空，默认推荐人服务商
                            if($inviter!=''){
                                $inviterId  =  $inviter;
                            }else{
                                $inviterId  ="";
                            }
                        }
                    $memberId =autoId();
                    $data = array(
                        'inviterId' => $inviterId,
                        'invitationCode' => $invitationCode,
                        'providerId' => $providerId,
                        'areaId' => $areaId,
                        'mobile' => $phone,
                        'memberName' => $phone,
                        'froms' => 'pc',
                        'addDateTime' => date('y-m-d h:i:s',time()),
                        'memberId' =>$memberId,
                        'loginPwd' =>pwd_hash(input('loginPwd')),
                    );
                    $result = Db::name('member')->insert($data);
                    Db::name('member_account')->insert(array('memberId'=>$memberId));
                    $coupon =   Db::name('param s')
                        ->join('coupon sos','sos.couponCode=s.paramValue')
                        ->where(array('paramCode'=>'REGISTER_MEMBER_COUPON','sos.isEnable'=>1))->find();
                    if($coupon){
                        $s=  $coupon['expire']*24*60*60;
                        $time = time()+$s;
                        $expiryDate = date('y-m-d H:i:s',$time);
                        $buyer_coupon = array(
                            "buyerCouponId" =>autoId(),
                            "memberId"  =>$memberId ,
                            "providerId"  =>getProviderId() ,
                            "couponId"  => $coupon['couponId'],
                            "expiryDate"  =>$expiryDate,
                            "category"  =>$coupon['categoryId'],
                            "status"  =>0,
                            "addDateTime"  =>date('y-m-d H:i:s',time()),
                        );
                        Db::name('buyer_coupon')->insert($buyer_coupon);
                    }
                    if($result){
                        $where =array('memberId'=>$memberId);
                        $user_info = Db::name("member")->where($where)->find();
                        $res['code'] = 'ok';
                        $res['msg'] = $memberId;
                        Session('Login_userId', $user_info['memberId']);
                        Session('Login_userName', $user_info['memberName']);
                    }else{
                        $res['code'] = 'fail';
                        $res['msg'] = '注册失败';
                    }

                }else{
                    $res['type'] = 'smsCode';
                    $res['code'] = 'fail';
                    $res['msg'] = '短信验证码超时';
                    Session::delete($phone.'_sendTime');
                    Session::delete($phone.'_smsCode');
                }
            }else{
                $res['type'] = 'smsCode';
                $res['code'] = 'fail';
                $res['msg'] = '短信验证码错误';
            }
            return $res;
        }else{
            $invitationCode = input('invitationCode');
            if(isset($invitationCode)){
                $this->view->assign('invitationCode',$invitationCode);
            }
            return view('register');
        }
    }
    public function logout()
    {
        if (Session('Login_userId')) {
            Session::clear();
               $this->redirect('/index');die;
        } else {
              $this->redirect('/index');die;
        }
    }
    //找回密码验证手机
    public  function findpwdCheckMobile(){
        $sms_code = input('sms_code');
        $providerId =  getProviderId();
        $phone = input('phone');
        if($phone != '') {
            //查询此会员是否已存在
            $where = array(
                'mobile' => $phone,
                'providerId' => $providerId,
                'memberType' => '0',
            );
            $user = Db::name('member')->where($where)->value('memberId');
            if($user !=''){
                //发送验证码
                $SmsSend = new \app\index\controller\SmsSend();
                $res =  $SmsSend -> index($sms_code,$phone);
            }else{
                $res['code'] = 'fail';
                $res['msg'] = '会员不存在';
            }
        }else{
            $res['code'] = 'fail';
            $res['msg'] = 'mobile不能为空';
        }
        return $res;
    }
    //找回密码
    public function findpwd()
    {
        if(Request::instance()->method() == 'POST') {
            $providerId =  getProviderId();
            //检查短信验证码
            $sms_code = input('smsCode');
            $phone = input('mobile');
            if($sms_code == Session($phone.'_smsCode')){
                //查询该手机号验证码是否过期
                $sendTime =  Session($phone.'_sendTime') ;
                $nowTime =  time();
                $sms_code_expire  =    Db::name('param')->where(array('paramCode' => 'VERIFY_CODE_INPUT_LIMIT','isEnable' => '1'))->value('paramValue');
                if($nowTime - $sendTime < ($sms_code_expire * 60)){
                    $memberId =  Db::name('member')->where(array('mobile' =>input('mobile'), 'providerId'=>$providerId, 'memberType'=>'0',) )->value('memberId');
                    //更新数据
                    $data = array(
                        'loginPwd' => pwd_hash(input('loginPwd')),
                        'memberId' => $memberId,
                    );
                    $where = array(
                        'mobile' =>input('mobile'),
                        'providerId'=>$providerId,
                        'memberType'=>'0',
                    )  ;
                    $loginPwd = Db::name('member') ->where($where)->value('loginPwd');
                    if($loginPwd == pwd_hash(input('loginPwd'))){
                        $res['code'] = 'ok';
                        $res['msg'] = '重置成功';
                        return $res;
                    }
                    $result = Db::name('member') ->where($where)->update($data);
                    if($result){
                        $res['code'] = 'ok';
                        $res['msg'] = '重置成功';
                    }else{
                        $res['code'] = 'fail';
                        $res['msg'] = '重置失败';
                    }
                }else{
                    $res['type'] = 'smsCode';
                    $res['code'] = 'fail';
                    $res['msg'] = '短信验证码超时';
                    Session::delete($phone.'_sendTime');
                    Session::delete($phone.'_smsCode');
                }
            }else{
                $res['type'] = 'smsCode';
                $res['code'] = 'fail';
                $res['msg'] = '短信验证码错误';
            }
            return $res;
        }else{
            $code=getFooter();

            $this->view->assign('code',$code);
            return view('findpwd');
        }
    }
}